#include <curl/curl.h>


static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}
 
std::string curl(const char* url,const char* postFields=NULL)
{
	CURL *curl;
    CURLcode res;
    std::string readBuffer;
 
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        // 指定URL
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 指定post内容
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        // 执行CURL访问网站
        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        } else {
            std::cout << readBuffer << std::endl;
        }
 
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
 
    return readBuffer;
}

std::string curl2(const char* url)
{
    CURL *curl;
    CURLcode res;
    std::string readBuffer;
    // 初始化模块
    curl_global_init(CURL_GLOBAL_DEFAULT);
    // 初始化请求库
    curl = curl_easy_init();
    if(curl)
    {
        // CURLOPT_URL 请求的网站
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // CURLOPT_WRITEFUNCTION 设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        // curl_easy_setopt(curl, CURLOPT_POST,1L);
        // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
        // curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,data.length());
        // curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
        // 执行CURL访问网站
        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        } else {
            // std::cout << readBuffer << std::endl;
        }
 
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    
    return readBuffer;
}
